import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Button, 
  Typography, 
  Grid, 
  Card, 
  CardContent, 
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  CircularProgress,
  Divider,
  Chip,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import VisibilityIcon from '@mui/icons-material/Visibility';
import TimelineIcon from '@mui/icons-material/Timeline';
import CloseIcon from '@mui/icons-material/Close';
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import FileUploadIcon from '@mui/icons-material/FileUpload';
import BackupIcon from '@mui/icons-material/Backup';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import DateRangeIcon from '@mui/icons-material/DateRange';
import MonetizationOnIcon from '@mui/icons-material/MonetizationOn';
import ShowChartIcon from '@mui/icons-material/ShowChart';
import CloudDownloadIcon from '@mui/icons-material/CloudDownload';
import { CardActionArea, Tooltip } from '@mui/material';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip as ChartTooltip,
  Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import { Product, ProductListItem, TimeLabel } from '../../types/product';
import ProductForm from '../../components/ProductForm';
import { getAllProducts, deleteProduct, saveProduct } from '../../services/storage';
import NetWorthCrawler from '../../components/NetWorthCrawler';

// 注册 Chart.js 组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  ChartTooltip,
  Legend
);

// 为不同银行生成不同的渐变背景色
const getBankColor = (bankName: string): { main: string; gradient: string } => {
  let hash = 0;
  for (let i = 0; i < bankName.length; i++) {
    hash = bankName.charCodeAt(i) + ((hash << 5) - hash);
  }
  const h = hash % 360;
  return {
    main: `hsla(${h}, 70%, 98%, 0.8)`,
    gradient: `linear-gradient(135deg, hsla(${h}, 70%, 98%, 0.9) 0%, hsla(${(h + 30) % 360}, 70%, 98%, 0.8) 100%)`
  };
};

interface FileUploadHandlerProps {
  setFileUploading: (loading: boolean) => void;
  loadProducts: () => void;
}

// 生成CSV模板内容
const generateTemplateCSV = () => {
  const headers = [
    '# 基本信息（必填）',
    '',
    '银行名称,产品名称,近1个月年化收益率(%),成立以来年化收益率(%)',
    '示例银行,示例理财产品,3.50,4.20',
    '',
    '# 净值记录（从此行开始，可添加多行）',
    '',
    '净值日期(YYYY-MM-DD),单位净值',
    '2024-01-01,1.0000',
    '2024-01-02,1.0001',
    '2024-01-03,1.0002'
  ].join('\n');
  return headers;
};

// 下载CSV模板
const downloadTemplate = () => {
  const csvContent = generateTemplateCSV();
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = '理财产品导入模板.csv';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

// 导出当前所有产品数据
const exportProductsData = (products: Product[]) => {
  try {
    if (products.length === 0) {
      alert('没有产品数据可导出');
      return;
    }
    
    const csvRows: string[] = [];
    
    // 遍历每个产品
    for (const product of products) {
      const oneMonthRate = product.historyRates.find(
        rate => rate.timeLabel === TimeLabel.OneMonth
      );
      const establishmentRate = product.historyRates.find(
        rate => rate.timeLabel === TimeLabel.SinceEstablishment
      );
      
      // 添加产品标题
      csvRows.push(`# ${product.name} - ${product.bank}`);
      csvRows.push('');
      
      // 添加基本信息表头和数据
      csvRows.push('银行名称,产品名称,近1个月年化收益率(%),成立以来年化收益率(%)');
      csvRows.push([
        product.bank,
        product.name,
        oneMonthRate?.advertisedRate || '',
        establishmentRate?.advertisedRate || ''
      ].join(','));
      csvRows.push('');
      
      // 添加净值记录表头
      csvRows.push('净值日期(YYYY-MM-DD),单位净值');
      
      // 添加最新净值记录
      csvRows.push(`${product.netWorthDate},${product.netWorth}`);
      
      // 添加历史净值记录
      product.netWorthHistory.forEach(record => {
        csvRows.push(`${record.date},${record.value}`);
      });
      
      // 在产品之间添加空行
      csvRows.push('');
      csvRows.push('');
    }
    
    // 组合CSV内容
    const csvContent = csvRows.join('\n');
    
    // 获取当前时间，格式化为 YYYY-MM-DD_HH-mm-ss
    const now = new Date();
    const timestamp = now.getFullYear() +
      '-' + String(now.getMonth() + 1).padStart(2, '0') +
      '-' + String(now.getDate()).padStart(2, '0') +
      '_' + String(now.getHours()).padStart(2, '0') +
      '-' + String(now.getMinutes()).padStart(2, '0') +
      '-' + String(now.getSeconds()).padStart(2, '0');
    
    // 创建Blob并下载
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8-sig' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `理财产品数据_${timestamp}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  } catch (error) {
    console.error('导出数据失败:', error);
    alert('导出数据失败，请重试');
  }
};

// 处理CSV文件导入
const handleFileUpload = (
  event: React.ChangeEvent<HTMLInputElement>,
  { setFileUploading, loadProducts }: FileUploadHandlerProps
) => {
  const file = event.target.files?.[0];
  if (!file) return;

  setFileUploading(true);

  const reader = new FileReader();
  reader.onload = async (e) => {
    try {
      const text = e.target?.result as string;
      const lines = text.split('\n').map(line => line.trim());
      
      const currentDate = new Date();
      let importedCount = 0;
      let currentProduct: Product | null = null;
      let isReadingNetWorthData = false;
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        
        // 跳过空行和注释行
        if (!line || line.startsWith('#')) {
          if (line.includes('净值记录')) {
            isReadingNetWorthData = true;
          }
          continue;
        }
        
        // 如果不是在读取净值数据，且行包含逗号，则认为是基本信息
        if (!isReadingNetWorthData && line.includes(',')) {
          const [bank, name, oneMonthRate, establishmentRate] = 
            line.split(',').map(item => item.trim());
            
          if (!bank || !name) continue; // 跳过不完整的行
          
          // 创建新的产品对象
          currentProduct = {
            id: `product_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
            bank,
            name,
            netWorth: 1.0, // 将在读取净值数据时更新
            netWorthDate: '', // 将在读取净值数据时更新
            historyRates: [
              {
                id: `rate_1m_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
                timeLabel: TimeLabel.OneMonth,
                advertisedRate: parseFloat(oneMonthRate) || 0,
                dailyProfit: 0, // 每万份收益将通过计算得出
                startDate: new Date(),
                endDate: new Date(),
                rate: parseFloat(oneMonthRate) || 0
              },
              {
                id: `rate_est_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
                timeLabel: TimeLabel.SinceEstablishment,
                advertisedRate: parseFloat(establishmentRate) || 0,
                dailyProfit: 0, // 每万份收益将通过计算得出
                startDate: new Date(),
                endDate: new Date(),
                rate: parseFloat(establishmentRate) || 0
              }
            ],
            netWorthHistory: [],
            investments: [],
            createdAt: currentDate,
            updatedAt: currentDate
          };
        }
        // 如果是在读取净值数据，且有当前产品对象
        else if (isReadingNetWorthData && currentProduct && line.includes(',')) {
          const [netWorthDate, netWorthValue] = line.split(',').map(item => item.trim());
          
          if (!netWorthDate || !netWorthValue) continue;
          
          const dateObj = new Date(netWorthDate);
          if (isNaN(dateObj.getTime())) continue; // 跳过无效日期
          
          const netWorth = parseFloat(netWorthValue);
          if (isNaN(netWorth)) continue; // 跳过无效净值
          
          // 第一条净值记录作为产品的当前净值
          if (!currentProduct.netWorthDate) {
            currentProduct.netWorth = netWorth;
            currentProduct.netWorthDate = netWorthDate;
            
            // 更新收益率记录的日期
            const oneMonthAgo = new Date(dateObj);
            oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
            
            currentProduct.historyRates.forEach(rate => {
              rate.endDate = dateObj;
              if (rate.timeLabel === TimeLabel.OneMonth) {
                rate.startDate = oneMonthAgo;
              } else {
                rate.startDate = new Date(dateObj.getFullYear() - 1, dateObj.getMonth(), dateObj.getDate());
              }
            });
          }
          // 其他净值记录添加到历史记录中
          else {
            currentProduct.netWorthHistory.push({
              id: `nw_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
              date: netWorthDate,
              value: netWorth
            });
          }
        }
        
        // 如果遇到空行或者是最后一行，且有当前产品对象，则保存产品
        if ((line === '' || i === lines.length - 1) && currentProduct) {
          if (currentProduct.netWorthDate) { // 只保存有净值数据的产品
            await saveProduct(currentProduct);
            importedCount++;
            currentProduct = null;
            isReadingNetWorthData = false;
          }
        }
      }
      
      // 使用组件内部的loadProducts函数
      loadProducts();
      setFileUploading(false);
      alert(`数据导入成功！共导入 ${importedCount} 条记录。`);
    } catch (error) {
      console.error('导入失败:', error);
      alert('导入失败，请检查文件格式是否正确！');
    }
  };
  reader.readAsText(file, 'utf-8');
  
  // 清空input的value，确保同一文件可以重复上传
  event.target.value = '';
};

const ProductsPage: React.FC = () => {
  const [products, setProducts] = useState<ProductListItem[]>([]);
  const [openForm, setOpenForm] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [showNetWorthChart, setShowNetWorthChart] = useState<string | null>(null);
  const [addingNetWorth, setAddingNetWorth] = useState(false);
  const [fileUploading, setFileUploading] = useState(false);
  const [showCrawler, setShowCrawler] = useState(false);

  useEffect(() => {
    loadProducts();
  }, []);

  const loadProducts = () => {
    try {
      const allProducts = getAllProducts();
      const productList: ProductListItem[] = allProducts.map(product => ({
        id: product.id,
        bank: product.bank,
        name: product.name,
        netWorth: product.netWorth,
        netWorthDate: product.netWorthDate,
        averageDailyProfit: product.historyRates.reduce((sum, rate) => 
          sum + rate.dailyProfit, 0) / (product.historyRates.length || 1),
        oneMonthRate: product.historyRates.find(
          rate => rate.timeLabel === TimeLabel.OneMonth
        )?.advertisedRate,
        establishmentRate: product.historyRates.find(
          rate => rate.timeLabel === TimeLabel.SinceEstablishment
        )?.advertisedRate,
      }));

      setProducts(productList);
    } catch (error) {
      console.error('加载产品列表失败:', error);
      setProducts([]);
    }
  };

  const handleAddNetWorth = async (productId: string) => {
    try {
      const allProducts = getAllProducts();
      const product = allProducts.find(p => p.id === productId);
      if (!product) return;

      setSelectedProduct(product);
      setAddingNetWorth(true);
      setOpenForm(true);
    } catch (error) {
      console.error('加载产品详情失败:', error);
    }
  };
  
  const handleCrawlNetWorth = async (productId: string) => {
    try {
      const allProducts = getAllProducts();
      const product = allProducts.find(p => p.id === productId);
      if (!product) return;

      setSelectedProduct(product);
      setShowCrawler(true);
    } catch (error) {
      console.error('加载产品详情失败:', error);
    }
  };

  const handleShowNetWorthChart = (productId: string) => {
    setShowNetWorthChart(productId);
  };

  const getNetWorthChartData = (productId: string) => {
    const product = getAllProducts().find(p => p.id === productId);
    if (!product) return null;

    // 合并最新净值和历史净值记录，并按日期排序
    const allRecords = [
      ...product.netWorthHistory,
      { id: 'latest', date: product.netWorthDate, value: product.netWorth }
    ].sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());

    return {
      labels: allRecords.map(record => 
        new Date(record.date).toLocaleDateString('zh-CN')
      ),
      datasets: [
        {
          label: '单位净值',
          data: allRecords.map(record => record.value),
          borderColor: 'rgb(75, 192, 192)',
          backgroundColor: 'rgba(75, 192, 192, 0.5)',
          tension: 0.1,
        }
      ]
    };
  };

  const handleAddProduct = () => {
    setSelectedProduct(null);
    setAddingNetWorth(false);
    setOpenForm(true);
  };

  const handleEditProduct = (productId: string) => {
    try {
      const allProducts = getAllProducts();
      const product = allProducts.find(p => p.id === productId);
      if (product) {
        setSelectedProduct(product);
        setAddingNetWorth(false);
        setOpenForm(true);
      }
    } catch (error) {
      console.error('加载产品详情失败:', error);
    }
  };

  const handleDeleteProduct = async (id: string) => {
    if (window.confirm('确定要删除这个产品吗？')) {
      try {
        deleteProduct(id);
        loadProducts();
      } catch (error) {
        console.error('删除产品失败:', error);
      }
    }
  };

  const handleFormClose = () => {
    setOpenForm(false);
    setSelectedProduct(null);
    setAddingNetWorth(false);
    loadProducts();
  };
  
  const handleCrawlerClose = () => {
    setShowCrawler(false);
    setSelectedProduct(null);
    loadProducts();
  };

  const formatMoney = (value: number): string => {
    return value.toFixed(4);
  };

  const formatRate = (rate?: number): string => {
    return rate ? `${rate.toFixed(2)}%` : '-';
  };

  const formatUpdateTime = (date?: Date): string => {
    if (!date) return '';
    return new Date(date).toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  return (
    <Box>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h5">理财产品收藏</Typography>
        <Box display="flex" gap={2}>
          <Button
            variant="outlined"
            startIcon={<FileDownloadIcon />}
            onClick={downloadTemplate}
          >
            下载导入模板
          </Button>
          <Button
            variant="outlined"
            component="label"
            startIcon={<FileUploadIcon />}
            disabled={fileUploading}
          >
            {fileUploading ? '导入中...' : '导入数据'}
            <input
              type="file"
              hidden
              accept=".csv"
              onChange={(e) => handleFileUpload(e, { setFileUploading, loadProducts })}
              disabled={fileUploading}
            />
          </Button>
          <Button
            variant="outlined"
            startIcon={<BackupIcon />}
            onClick={() => exportProductsData(getAllProducts())}
          >
            导出数据
          </Button>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={handleAddProduct}
          >
            添加理财产品
          </Button>
        </Box>
      </Box>

      <Grid container spacing={3}>
        {products.map((product) => (
          <Grid item xs={12} sm={6} md={4} key={product.id}>
            <Card 
              sx={{ 
                height: '100%',
                background: getBankColor(product.bank).gradient,
                transition: 'all 0.3s ease-in-out',
                border: '1px solid rgba(0, 0, 0, 0.05)',
                borderRadius: 2,
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
                overflow: 'hidden',
                '&:hover': {
                  transform: 'translateY(-4px)',
                  boxShadow: '0 8px 24px rgba(0, 0, 0, 0.1)',
                }
              }}
            >
              <CardActionArea onClick={() => handleShowNetWorthChart(product.id)}>
                <CardContent>
                  <Box display="flex" justifyContent="space-between" alignItems="flex-start">
                    <Box width="100%">
                          <Box display="flex" alignItems="center" mb={2.5}>
                            <AccountBalanceIcon 
                              sx={{ 
                                mr: 1.5, 
                                color: 'primary.main',
                                fontSize: 28,
                                filter: 'drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1))'
                              }} 
                            />
                            <Box>
                              <Typography 
                                variant="h6" 
                                component="div" 
                                sx={{ 
                                  lineHeight: 1.2,
                                  fontWeight: 600,
                                  letterSpacing: '-0.01em',
                                  mb: 0.5
                                }}
                              >
                                {product.name}
                              </Typography>
                              <Typography 
                                color="textSecondary" 
                                variant="body2"
                                sx={{
                                  fontWeight: 500,
                                  backgroundColor: 'rgba(0, 0, 0, 0.04)',
                                  px: 1,
                                  py: 0.25,
                                  borderRadius: 1,
                                  display: 'inline-block'
                                }}
                              >
                                {product.bank}
                              </Typography>
                            </Box>
                          </Box>
                      <Divider sx={{ my: 1.5 }} />
                      <Grid container spacing={2} sx={{ mt: 1 }}>
                        <Grid item xs={12}>
                          <Box display="flex" alignItems="center">
                            <ShowChartIcon sx={{ mr: 1, color: 'success.main' }} />
                            <Typography variant="body2" sx={{ fontWeight: 500 }}>
                              单位净值：
                              <Typography 
                                component="span" 
                                color="success.main" 
                                sx={{ 
                                  fontWeight: 'bold',
                                  backgroundColor: 'rgba(76, 175, 80, 0.1)',
                                  px: 1,
                                  py: 0.25,
                                  borderRadius: 1,
                                  ml: 0.5
                                }}
                              >
                                {formatMoney(product.netWorth)}
                              </Typography>
                            </Typography>
                            <Chip 
                              size="small" 
                              icon={<DateRangeIcon />}
                              label={new Date(product.netWorthDate).toLocaleDateString()}
                              sx={{ 
                                ml: 1, 
                                height: 20,
                                backgroundColor: 'rgba(0, 0, 0, 0.04)',
                                '& .MuiChip-icon': {
                                  color: 'text.secondary',
                                  fontSize: 14
                                }
                              }}
                            />
                          </Box>
                        </Grid>
                        <Grid item xs={12}>
                          <Box display="flex" alignItems="center">
                            <MonetizationOnIcon sx={{ mr: 1, color: 'primary.main' }} />
                            <Typography variant="body2" sx={{ fontWeight: 500 }}>
                              平均每万份收益：
                              <Typography 
                                component="span" 
                                color="primary.main" 
                                sx={{ 
                                  fontWeight: 'bold',
                                  backgroundColor: 'rgba(25, 118, 210, 0.1)',
                                  px: 1,
                                  py: 0.25,
                                  borderRadius: 1,
                                  ml: 0.5
                                }}
                              >
                                {formatMoney(product.averageDailyProfit)}元
                              </Typography>
                            </Typography>
                          </Box>
                        </Grid>
                        <Grid item xs={12}>
                          <Box display="flex" alignItems="center">
                            <TrendingUpIcon sx={{ mr: 1, color: 'info.main' }} />
                            <Typography variant="body2" sx={{ fontWeight: 500 }}>
                              {product.oneMonthRate ? '近1个月年化' : '成立以来年化'}：
                              <Typography 
                                component="span" 
                                color="info.main" 
                                sx={{ 
                                  fontWeight: 'bold',
                                  backgroundColor: 'rgba(2, 136, 209, 0.1)',
                                  px: 1,
                                  py: 0.25,
                                  borderRadius: 1,
                                  ml: 0.5
                                }}
                              >
                                {formatRate(product.oneMonthRate || product.establishmentRate)}
                              </Typography>
                            </Typography>
                          </Box>
                        </Grid>
                      </Grid>
                    </Box>
                  </Box>
                  <Divider sx={{ my: 1.5 }} />
                  <Box 
                    display="flex" 
                    justifyContent="flex-end" 
                    gap={1}
                    sx={{
                      '& .MuiIconButton-root': {
                        transition: 'all 0.2s ease-in-out',
                        '&:hover': {
                          transform: 'scale(1.1)',
                        }
                      }
                    }}
                  >
                    <Tooltip title="抓取净值数据">
                      <IconButton
                        size="small"
                        color="secondary"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleCrawlNetWorth(product.id);
                        }}
                      >
                        <CloudDownloadIcon />
                      </IconButton>
                    </Tooltip>
                    <Tooltip title="添加净值">
                      <IconButton
                        size="small"
                        color="primary"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleAddNetWorth(product.id);
                        }}
                      >
                        <AddCircleOutlineIcon />
                      </IconButton>
                    </Tooltip>
                    <Tooltip title="编辑">
                      <IconButton
                        size="small"
                        color="info"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleEditProduct(product.id);
                        }}
                      >
                        <EditIcon />
                      </IconButton>
                    </Tooltip>
                    <Tooltip title="删除">
                      <IconButton
                        size="small"
                        color="error"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDeleteProduct(product.id);
                        }}
                      >
                        <DeleteIcon />
                      </IconButton>
                    </Tooltip>
                    <Tooltip title="查看净值走势">
                      <IconButton
                        size="small"
                        color="success"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleShowNetWorthChart(product.id);
                        }}
                      >
                        <TimelineIcon />
                      </IconButton>
                    </Tooltip>
                  </Box>
                </CardContent>
              </CardActionArea>
            </Card>
          </Grid>
        ))}

        {products.length === 0 && (
          <Grid item xs={12}>
            <Typography color="textSecondary" align="center">
              暂无产品，点击"添加理财产品"按钮开始添加
            </Typography>
          </Grid>
        )}
      </Grid>

      <Dialog
        open={openForm}
        onClose={handleFormClose}
        maxWidth="md"
        fullWidth
      >
        <ProductForm
          product={selectedProduct}
          onClose={handleFormClose}
          addingNetWorth={addingNetWorth}
        />
      </Dialog>

      {/* 净值抓取对话框 */}
      {showCrawler && selectedProduct && (
        <NetWorthCrawler
          product={selectedProduct}
          onClose={handleCrawlerClose}
          onSuccess={loadProducts}
        />
      )}

      <Dialog
        open={!!showNetWorthChart}
        onClose={() => setShowNetWorthChart(null)}
        maxWidth="md"
        fullWidth
      >
        {showNetWorthChart && (
          <>
            <DialogTitle>
              {products.find(p => p.id === showNetWorthChart)?.name} - 单位净值走势
            </DialogTitle>
            <DialogContent>
              <Box py={2}>
                <Line 
                  data={getNetWorthChartData(showNetWorthChart)!}
                  options={{
                    responsive: true,
                    plugins: {
                      legend: {
                        position: 'top' as const,
                      },
                      tooltip: {
                        callbacks: {
                          label: (context) => {
                            const value = context.parsed.y;
                            return `单位净值: ${value.toFixed(4)}`;
                          }
                        }
                      }
                    },
                    scales: {
                      y: {
                        beginAtZero: false,
                        ticks: {
                          callback: function(tickValue: number | string): string {
                            if (typeof tickValue === 'number') {
                              return tickValue.toFixed(4);
                            }
                            return tickValue;
                          }
                        }
                      }
                    }
                  }}
                />
              </Box>
            </DialogContent>
          </>
        )}
      </Dialog>
    </Box>
  );
};

export default ProductsPage;
export {};